﻿Shader "TriPlanar"
{
    Properties
    {
        _BaseMap("Base Map", 2D) = "white" {}
        _Smooth("Smooth",Range(1,10)) = 5
        [KeywordEnum (World,Local)] SPECULARTYPE("Type", Float) = 0
    }
    SubShader
    {
        Tags
        {
            "RenderPipeline" = "UniversalPipeline"
            "LightMode" = "UniversalForward"
            "Queue" = "Geometry"
        }

        HLSLINCLUDE
        #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
        #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"

        #pragma shader_feature_fragment SPECULARTYPE_WORLD SPECULARTYPE_LOCAL
        
        TEXTURE2D(_BaseMap);
        SAMPLER(sampler_BaseMap);

        CBUFFER_START(UnityPerMaterial)
            half4 _BaseMap_ST;
            half _Smooth;
        CBUFFER_END
        ENDHLSL

        pass
        {
            HLSLPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            struct a2v
            {
                float4 positionOS   : POSITION;
                float3 normalOS     : NORMAL;
                float2 texcoord     : TEXCOORD;
            };

            struct v2f
            {
                float4 positionCS   : SV_POSITION;
                float3 positionWS   : TEXCOORD0;
                float3 normalWS     : NORMAL;
            };

            v2f vert(a2v input)
            {
                v2f output;
                output.positionCS = TransformObjectToHClip(input.positionOS.xyz);
                output.positionWS = TransformObjectToWorld(input.positionOS.xyz);
                output.normalWS = TransformObjectToWorldNormal(input.normalOS.xyz);
                
                return output;
            }

            half4 TriPlanar(TEXTURE2D_PARAM(map, sampler_map),half4 map_ST, float3 normalWS, float3 position, float smooth)
            {
                half3 n = pow(abs(normalWS), smooth * 10);
                n /= (n.x + n.y + n.z);
                
                half4 c1 = SAMPLE_TEXTURE2D(map, sampler_map, position.xy * map_ST.xy + map_ST.zw) * n.z;
                half4 c2 = SAMPLE_TEXTURE2D(map, sampler_map, position.xz * map_ST.xy + map_ST.zw) * n.y;
                half4 c3 = SAMPLE_TEXTURE2D(map, sampler_map, position.zy * map_ST.xy + map_ST.zw) * n.x;
                return c1 + c2 + c3;
            }


            half4 frag(v2f input):SV_Target
            {
                half3 normalWS = normalize(input.normalWS);

                half3 pos = half3(0, 0, 0);
                #if SPECULARTYPE_WORLD
                     pos = input.positionWS;
                #else
                    pos = TransformWorldToObject(input.positionWS);
                #endif

                half4 final = TriPlanar(_BaseMap, sampler_BaseMap, _BaseMap_ST, normalWS, pos, _Smooth);
                return final;
            }
            ENDHLSL
        }
    }
}